package com.signin.controller;

import com.signin.model.dto.SignInSessionDTO;
import com.signin.model.dto.StudentSignInDTO;
import com.signin.model.entity.SignInRecord;
import com.signin.service.SignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/sign-in")
public class SignInController {

    @Autowired
    private SignInService signInService;
    
    // 查询历史签到会话（支持分页）
    @GetMapping("/history")
    public ResponseEntity<?> queryHistoricalSessions(
            @RequestParam(required = false) String classroom,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 计算偏移量
            int offset = (page - 1) * pageSize;
            // 调用服务层方法获取分页数据
            Map<String, Object> result = signInService.queryHistoricalSessions(classroom, startDate, endDate, page, pageSize);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "查询历史签到会话失败：" + e.getMessage()));
        }
    }

    // 创建签到会话
    @PostMapping("/sessions")
    public ResponseEntity<?> createSignInSession(@RequestBody SignInSessionDTO sessionDTO) {
        try {
            SignInSessionDTO createdSession = signInService.createSignInSession(sessionDTO);
            return ResponseEntity.ok(createdSession);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("error", e.getMessage()));
        }
    }

    // 开始签到
    @PutMapping("/sessions/{id}/start")
    public ResponseEntity<?> startSignIn(@PathVariable("id") Long sessionId) {
        boolean success = signInService.startSignIn(sessionId);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("success", false, "error", "开始签到失败"));
        }
    }

    // 结束签到
    @PutMapping("/sessions/{id}/end")
    public ResponseEntity<?> endSignIn(@PathVariable("id") Long sessionId) {
        boolean success = signInService.endSignIn(sessionId);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("success", false, "error", "结束签到失败"));
        }
    }

    // 学生签到
    @PostMapping("/sessions/{id}/records")
    public ResponseEntity<?> studentSignIn(@PathVariable("id") Long sessionId, @RequestBody StudentSignInDTO signInDTO) {
        boolean success = signInService.studentSignIn(sessionId, signInDTO);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true, "message", "签到成功"));
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("success", false, "message", "签到失败"));
        }
    }

    // 获取签到会话信息
    @GetMapping("/sessions/{id}")
    public ResponseEntity<?> getSignInSession(@PathVariable("id") Long sessionId) {
        SignInSessionDTO sessionDTO = signInService.getSignInSession(sessionId);
        if (sessionDTO != null) {
            return ResponseEntity.ok(sessionDTO);
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("error", "签到会话不存在"));
        }
    }

    // 获取签到记录
    @GetMapping("/sessions/{id}/records")
    public ResponseEntity<?> getSignInRecords(@PathVariable("id") Long sessionId) {
        List<SignInRecord> records = signInService.getSignInRecords(sessionId);
        return ResponseEntity.ok(records);
    }
    
    // 踢出签到学生
    @DeleteMapping("/sessions/{id}/records")
    public ResponseEntity<?> kickOutStudent(
            @PathVariable("id") Long sessionId,
            @RequestParam("studentName") String studentName) {
        try {
            boolean success = signInService.kickOutStudent(sessionId, studentName);
            if (success) {
                return ResponseEntity.ok(Map.of("success", true, "message", "学生踢出成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("success", false, "message", "踢出失败，签到会话不存在或非进行中状态"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "踢出失败：" + e.getMessage()));
        }
    }

    // 获取当前活动的签到会话
    @GetMapping("/sessions/active")
    public ResponseEntity<?> getActiveSession() {
        SignInSessionDTO sessionDTO = signInService.getCurrentActiveSession();
        return ResponseEntity.ok(sessionDTO);
    }
}